<?php
namespace Admin\Controller;

use Admin\Controller\BaseController;
use Admin\Model\StarbuyFlashsalesModel;
use Think\Controller;
use Think\Exception;

class FlashsalesController extends BaseController
{
    public $obj;
    public $local_id;
    public $time_obj;
    public $product_obj;

    public function __construct()
    {
        parent::__construct();
        $this->obj = new StarbuyFlashsalesModel();
        $this->time_obj = M('starbuy_flashsales_time');
        $this->product_obj = M('starbuy_flashsales_goods');
        $this->_arr['title'] = '营销';
        $this->local_id = session('userInfo')['local_id'];
        if(!$this->local_id){
            $this->error('请登录', '/admin/login/index');
        }
    }

    public function index()
    {
        $this->_arr['title_two'] = '限时抢购';
        $this->_arr['p'] = I('p', 1, 'intval');
        $this->_arr['select'] = I('select');
        $this->_arr['value'] = trim(I('value'));
        $this->_arr['begintime'] = I('begintime');
        $this->_arr['endtime'] = I('endtime');
        $where = 'local_id='.$this->local_id;
        if($this->_arr['begintime'] || $this->_arr['endtime']){
            if($this->_arr['begintime'] != $this->_arr['endtime']){
                if($this->_arr['begintime']){
                    $where .= " and sf.flashsales_date >= '".$this->_arr['begintime']."'";
                }
                if($this->_arr['endtime']){
                    $where .= " and sf.flashsales_date < '".$this->_arr['endtime']."'";
                }
            }else{
                $where .= " and sf.flashsales_date ='".$this->_arr['endtime']."'";
            }
        }

        if($this->_arr['select'] && $this->_arr['value']){
            switch($this->_arr['select']){
                case 'id' :
                    $where .= ' and sf.special_id = '.$this->_arr['value'];
                    break;
                case 'name' :
                    $where .= " and sf.name like '".$this->_arr['value']."%'";
                    break;
            }
        }

        $special_id = I('id') ? I('id') : 2;
        if ($special_id == 1) {
            $order = 'special_id asc';
            $this->_arr['rank'] = 2;
        } elseif ($special_id == 2) {
            $order = 'special_id desc';
            $this->_arr['rank'] = 1;
        }
        $data = $this->obj->alias('sf')
            ->field('sf.*')
            ->where($where)
            ->order($order)
            ->page($this->_arr['p'] . ','.$this->page_num)
            ->select();
        //echo $this->obj->_sql();
        $count = $this->obj->alias('m')
            ->where($where)
            ->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, $this->page_num);// 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page->show();// 分页显示输出
        $this->_arr['page'] = $show;// 赋值分页输出
        $this->_arr['list'] = $data;
        $this->_showDisplay();

    }

    /*
     * 闪购开启，禁止
     * */
    public function changeStart($is_start,$special_id){

        $mod = M();
        $mod->startTrans();


        try{
//            $res = M('starbuy_flashsales')->where(['special_id'=>$special_id])->save(['is_start'=>$is_start]);
            $res = M()->execute("UPDATE `sdb_starbuy_flashsales` SET `is_start`='$is_start' WHERE (`special_id`='$special_id')");

            if($res == false){ throw new Exception('2201');}

            if($is_start == '0'){
                $info = M('starbuy_flashsales_goods fg')
                    ->join('left join sdb_starbuy_flashsales_time ft on fg.tid = ft.tid')
                    ->join('left join sdb_starbuy_flashsales sf on ft.special_id = sf.special_id')
                    ->where(['fg.special_id'=>$special_id])
                    ->field('fg.initnum,fg.store_pid,fg.id')
                    ->select();
                foreach ($info as $k=>$v){
                    if ($v['initnum']> 0) {
                        $old_freez = M('b2c_store_product')->where(['store_pid' => $v['store_pid']])->setDec('freez',$v['initnum']);
                        $old_freez2 = M('starbuy_flashsales_goods')->where(['id' => $v['id']])->setDec('initnum',$v['initnum']);
                        if($old_freez ==false) {

                            throw  new Exception('2202');
                        }
                        if($old_freez2 ==false){

                            throw  new Exception('2203');
                        }
                    }
                }

            }
            $mod->commit();
            $this->success('修改成功');
        }catch (\Exception $e){
            $mod->rollback();
            $this->error('网络延迟，请稍候再试！, 错误码：'. $e->getMessage(),U('Flashsales/index'));
        }

    }


    /**
     * 时间段
     */
    public function timeIndex()
    {
        $this->_arr['special_id'] = I('get.special_id',0) or $this->error('参数错误！');
        if(!is_numeric($this->_arr['special_id'])){
            $this->error('参数错误！');
        }
        $data = M('starbuy_flashsales_time')->where(['special_id' => $this->_arr['special_id']]) ->select();
        foreach($data as $k1 => $v1){
            //状态（即将开始、已结束）
            $time =  time();

            if($v1['begin_time'] < $time && $time< $v1['end_time']){
                $data[$k1]['stat'] = '进行中';
                $data[$k1]['p'] = 0;
            }else if($time < $v1['begin_time']){
                $data[$k1]['stat'] = '即将开始';
                $data[$k1]['p'] = 1;
            }else if($time > $data['end_time']){
                $data[$k1]['stat'] = '已结束';
                $data[$k1]['p'] = 0;
            }
            $data[$k1]['begin_time'] = date('Y-m-d H:i:s',$v1['begin_time']);
            $data[$k1]['end_time'] = date('Y-m-d H:i:s',$v1['end_time']);

        }
        //dump($data);
        $this->_arr['list'] = $data;
        $this->_showDisplay();

    }

    /**
     * 新增一个时间段
     */
    public function addTime(){
        $this->_arr['special_id'] = I('special_id') or $this->error('参数错误！');
        $this->_showDisplay('Flashsales/saveTime');
    }
    /**
     * 修改一个时间段
     */
    public function saveTime(){
        $tid = I('get.tid',0) or $this->error('参数错误！');
        if(!is_numeric($tid)){
            $this->error('参数错误！');
        }
        $data = M('starbuy_flashsales_time')->where(['tid' => $tid]) ->find();
        //状态（即将开始、已结束）
        $time = time();
        //dump($time);
        //dump($data['begin_time']);
        //dump($data['end_time']);
        if($data['begin_time'] < $time && $time< $data['end_time']){
            //echo 1;
            $data['stat'] = '进行中';
            $data['p'] = 0;
        }else if($time < $data['begin_time']){
            //echo 2;
            $data['stat'] = '即将开始';
            $data['p'] = 1;
        }else if($time > $data['end_time']){
            //echo 3;
            $data['stat'] = '已结束';
            $data['p'] = 0;
        }
        $data['begin_time'] = date('Y-m-d H:i:s',$data['begin_time']);
        $data['end_time'] = date('Y-m-d H:i:s',$data['end_time']);
        //查询货品
        $g_data = M('starbuy_flashsales_goods')->alias('sfg')->field('sfg.*,sp.p_name,sp.price,sp.store,sp.freez')
            ->join(C('DB_PREFIX').'b2c_store_product sp on sp.store_pid = sfg.store_pid and sp.store_status="true"', 'LEFT')
            ->where( array('tid'=> $data['tid']))->select();
        $s_pids = '';
        foreach($g_data as $v1){
            $s_pids  .= $v1['store_pid'].'#';
        }
        $s_pids = trim($s_pids,'#');
        $data['products'] = $g_data;
        //dump($data);
        $this->_arr['msg'] = $data;
        $this->_arr['s_pids'] = $s_pids;
        $this->_arr['special_id'] = $data['special_id'];
        $this->_showDisplay();
    }

    /**
     * 店铺商品
     */
    public function getProducts() {
        $p = max(I('param.p'), 1);
        $num = max(I('param.num'), 15);
        $this->assign('page', $p);
        $this->assign('num', $num);


        $beginTime = I('get.beginTime', date('Y-m-d H:i'));
        $endTime = I('get.endTime', date('Y-m-d H:i'));

        $order_field = I('param.order_field', 'product_id');
        $order = I('param.order', 'desc');
        $sunxu = $order == 'asc' ? 'desc' : 'asc';
        $this->assign('order_field', $order_field);
        $this->assign('order', $sunxu);
        $order = array($order_field => $order);
        //字段（搜索）
        $search_field = I('param.search_field');
        //搜索的内容
        $search = trim(I('param.search'));
        $local_id = $this->local_id;
        $where[] = array('a.local_id' =>  $local_id);
        //过滤门店所有有活动的商品
//        $spids = M('store_activity_product')->where(['local_id' => $this->local_id,'end_time' => ['gt',time()]])->getField('store_pid',true);
//        if(!empty($spids)){
//            $where[] = ['a.store_pid' => ['not in',$spids]];
//        }
        $where[] = array('a.store_status' =>  'true');

        if ($search && $search_field) {
            if ($search_field == 'bn') {
                $sfield = 'a.'.$search_field;
            } else {
                $sfield = $search_field;
            }
            $where[] = $sfield." like '%".$search."%'";
            $this->assign('search',$search);
            $this->assign('search_field',$search_field);
        }
        $count = M('b2c_store_product a')
            ->join(C('DB_PREFIX').'b2c_store_cat b on a.scate_id = b.store_cat_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id and c.disabled = "false"' )
            ->join(C('DB_PREFIX').'b2c_goods g on a.goods_id = g.goods_id and g.disabled = "false"' )
            ->join(C('DB_PREFIX').'b2c_product_relation d on a.product_id = d.product_id and a.goods_id = d.goods_id and d.product_type_id = 1')
            ->where($where)
            ->count();
        $Page = new \Think\Page($count, $num, ['beginTime'=>$beginTime, 'endTime'=>$endTime]);
        $show = $Page->show();
        $fields = 'a.*,b.`cat_name`,c.`barcode`,c.`spec_info`';
        $list = M('b2c_store_product a')
            ->join(C('DB_PREFIX').'b2c_store_cat b on a.scate_id = b.store_cat_id', 'LEFT')
            ->join(C('DB_PREFIX').'b2c_products c on a.product_id = c.product_id and c.disabled = "false"' )
            ->join(C('DB_PREFIX').'b2c_goods g on a.goods_id = g.goods_id and g.disabled = "false"' )
            ->join(C('DB_PREFIX').'b2c_product_relation d on a.product_id = d.product_id and a.goods_id = d.goods_id and d.product_type_id = 1')
            ->field($fields)
            ->where($where)
            ->order($order)
            ->page($p, $num)
            ->select();
        $store_pid = I('product_ids');

        $date = I('date',0);
        $this->assign('date', $date);
        //dump($date);
        //$pids = $this->dayPorduct($date);
        foreach ($list as $k1 => $item) {
            //标记出已经选中的货品
            if ($store_pid) {
                $store_pids = explode("#", $store_pid);
                if (is_array($store_pids)) {
                    if (in_array($item['store_pid'], $store_pids)) {
                        $list[$k1]['is_show'] = true;
                    } else {
                        $list[$k1]['is_show'] = false;
                    }
                }
            }
            //过滤货品
//            if($list[$k1]['is_show'] == false){
//                if(is_array($pids)){
//                    if (in_array($item['store_pid'], $pids)) {
//                        unset($list[$k1]);
//                    }
//                }
//            }

        }
        $this->assign('limitTime', [
            'beginTime' => $beginTime,
            'endTime' => $endTime]);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->display();
    }

    /**
     * 获取某天的闪购商品id
     * @param string $date
     * @return mixed
     */
    public function dayPorduct($date = ''){
        if(!$date){
            $date = date('Y-m-d');//当天
        }

        $ids = $this->obj->alias('f')
            ->join(C('DB_PREFIX').'starbuy_flashsales_time t on f.special_id = t.special_id')
            ->join(C('DB_PREFIX').'starbuy_flashsales_goods g on t.tid = g.tid')
            ->where(['f.flashsales_date'=>$date])
            ->field('g.store_pid')
            ->select();
            //->getField('g.store_pid',true);
        return array_column($ids, 'store_pid');
    }


    /**
     * 新增闪购
     */
    public function addFlashsales(){

        $this->display();
    }

    /**
     * 修改闪购表
     */
    public function save_activity(){

        $ruledata = $_POST['ruledata'];
        $image_num = I('input-num'); // 默认的图片id
        if(!($ruledata['name'] = trim($ruledata['name']))){
            $this->error('闪购名称不能为空');
        }
        if(!($ruledata['flashsales_date'] = trim($ruledata['flashsales_date']))){
            $this->error('请选择时间');
        }
        //dump($ruledata['flashsales_date']);die;
        $images = I('images');
        $ruledata['local_id'] = $this->local_id;
        try{
            M()->execute('begin');
            if($ruledata['special_id']){
                $delete_images = M()->execute("DELETE p.*, pp.* FROM sdb_image_image p, sdb_image_image_attach pp WHERE	p.image_id = pp.image_id AND pp.target_id = ".$ruledata['special_id']." AND pp.target_type = 'FlashSales'");
                if ($delete_images === false) {
                    throw new \Exception('images delete error');
                }
            }

            // 添加image图片
            if (is_array($images) && !empty($images)) {

                for ($i = 0; $i < count($images); $i++) {
                    $image_data['url'] = $images[$i];

                    $images_thumb = explode("/", $images[$i]);
                    $l_url = '/' . $images_thumb[1] . '/' .$images_thumb[2] . '/' . 'l_'. $images_thumb[3];
                    $m_url = '/' . $images_thumb[1] . '/' . $images_thumb[2] . '/' . 'm_'. $images_thumb[3];
                    $s_url = '/' . $images_thumb[1] . '/' . $images_thumb[2] . '/' . 's_'. $images_thumb[3];

                    $image_data['l_url'] = $l_url;
                    $image_data['m_url'] = $m_url;
                    $image_data['s_url'] = $s_url;
                    $image_data['last_modified'] = time();
                    $image_data['image_id'] = md5(time() . $i);
                    $image_id = M('image_image')->add($image_data);
                    if ($image_id === false) {
                        throw new \Exception($i . 'image');
                    }

                    if ($i == $image_num) {
                        $target = $image_data['image_id'];
                    }
                    $image_id_array[] = $image_data['image_id'];
                }
            }
            $special_id = $ruledata['special_id'];
            if($special_id){
                $s = $this->obj->where(array('special_id' => $ruledata['special_id'],'local_id'=>$this->local_id))->data($ruledata)->save();
                //闪购一天只有一条
                $count = $this->obj->where(array('special_id' => $ruledata['special_id'],'local_id'=>$this->local_id,'is_start'=>'1'))->count();
                if( $count > 1){
                    throw new \Exception('一天只许一条闪购活动');
                }
                if($s === false) {
                    throw new \Exception('失败');
                }
                $url = U("Flashsales/timeIndex");
            }else{
                //闪购一天只有一条
                $s_data = $this->obj->where(array('flashsales_date'=> $ruledata['flashsales_date'],'local_id'=>$this->local_id,'is_start'=>'1'))->find();
                if($s_data){
                    throw new \Exception('一天只许一条闪购活动');
                }
                $ruledata['create_time'] = time();
                $special_id = $this->obj->add($ruledata);
                if($special_id === false){
                    throw new \Exception('失败');
                }

            }
            // 添加商品和图片关联表image_image_attach
            for ($j = 0; $j < count($image_id_array); $j++) {
                $image_image_attach_data['target_id'] = $special_id;
                $image_image_attach_data['image_id'] = $image_id_array[$j];
                $image_image_attach_data['target_type'] = 'FlashSales';
                $image_image_attach_data['last_modified'] = time();
                $image_image_attach_add = M('image_image_attach')->add($image_image_attach_data);
                if ($image_image_attach_add === false) {
                    throw new \Exception($j . 'attach');
                }
            }

            M()->execute('commit');

            $this->success('成功',U('Flashsales/index'));


        }catch (\Exception $e){
            M()->execute('rollback');
            $this->error('错误代码：' . $e->getMessage());
        }

    }

    /**
     * 修改初始化
     */
    public function saveFlashsales()
    {
        $id = I('special_id',0,'intval');
        if(!$id){
            $this->error('参数错误');
        }
        //$data = $this->obj->getList($id);
        $data = $this->obj->where(['special_id'=> $id])->find();
        // 图片
        $images = M('image_image_attach a')->join('left join sdb_image_image b on a.image_id = b.image_id')
            ->where(['a.target_id' => $id,'a.target_type' => 'FlashSales'])
            ->select();
        //dump($data);
        $this->assign('ruleInfo',$data);
        $this->assign('images',$images);
        $this->_showDisplay('Flashsales/addFlashsales');
    }

    /**
     * 判断商品是否在当前时间段内
     * @param $beginTime
     * @param $endTime
     * @param array $products
     * @return bool
     */
    private function checkProductIsTime($beginTime, $endTime, $products = array())
    {
        return false;
    }

    /**
     * 修改闪购时间段和闪购商品
     */
    public function save_rule()
    {
        $tid = I('tid',0);

        $time_data['special_id'] = I('special_id',0) or $this->error('未知错误，请从退出重新操作！');
        //判断闪购时间与时间段里是不是在同一天
        $flashsales_date = $this->obj->where(['special_id'=>$time_data['special_id']])->find()['flashsales_date'];
        $begin_time = I('begin_time',0);
        $end_time = I('end_time',0);
        $time_data['begin_time'] = $begin_time ? strtotime($begin_time) :  $this->error('请输入开始时间');

        $time_data['end_time'] = $end_time ? strtotime($end_time):$this->error('请输入结束时间');
        $begin_time = explode(' ',$begin_time);
        $end_time = explode(' ',$end_time);
        if($begin_time[0] != $flashsales_date || $end_time[0] != $flashsales_date){
            $this->error('时间段与闪购时间必须在一天');
        }
        $time_data['b_h_minute'] = substr($begin_time[1],0,5);
        $time_data['e_h_minute'] = substr($end_time[1],0,5);
        if(!($time_data['begin_time'] < $time_data['end_time'])){
            $this->error('开始时间不能大于或等于结束时间');
        }
        $time_data['limit'] = (I('limit',0) > 0) ? I('limit',0) : $this->error('限购数量必须大于0');
        if(!is_numeric($time_data['limit'])){
            $this->error('限购数量必为整数');
        }

        $model = M();
        try{
            $model->startTrans();
            if($tid){
                $time_status = M('starbuy_flashsales_time')->where(['tid'=>$tid])->save($time_data);
                if($time_status === false){
                    throw new \Exception('修改失败');
                }
            }else{
                $time_status = M('starbuy_flashsales_time')->add($time_data);
                if($time_status === false){
                    throw new \Exception('新增失败');
                }
                $tid = $time_status;
            }

            $store_pid = I('store_pid');
            $promotion_price = I('promotion_price');
            $initnum = I('initnum');
            //店铺货品表
            //查询已有的数据，冻结库存减回去
            $product_data = M('starbuy_flashsales_goods')->where(['tid'=>$tid])->select();
            foreach($product_data as $k1 => $v1){
                $s_p_data = M('b2c_store_product')->where(['store_pid' => $v1['store_pid'], 'store_status' => 'true'])->find();
                //$updata['store'] = $s_p_data['store'] + $v1['initnum'];
                $updata['freez'] = $s_p_data['freez'] - $v1['initnum'];
                if($updata['freez'] < 0){
                    throw new \Exception('失败');
                }
                //可用库存
               /* $storeNum = $s_p_data['store'] - $s_p_data['freez'];
                if($storeNum < $v1['initnum']){
                    throw new \Exception('闪购数量不能大于可用库存');
                }*/
                $s_p_status = M('b2c_store_product')->where(['store_pid' => $v1['store_pid'], 'store_status' => 'true'])->save($updata);

                //$s_p_status = M('b2c_store_product')->where(['store_pid' => $v1['store_pid']])->setDec('freez',$v1['initnum']);
                if($s_p_status === false){
                    throw new \Exception('失败');
                }
            }
            //删除
            $stat = M('starbuy_flashsales_goods')->where(['tid'=>$tid])->delete();//var_dump($stat);die;
            if($stat === false){
                throw new \Exception('失败');
            }
            //入库
            for($i = 0 ;$i < count($store_pid);$i++){
                if(!$store_pid[$i]){
                    throw new \Exception('ID错误！');
                }
                if(!$promotion_price[$i]){
                    throw new \Exception('价格不能为空！');
                }
                if(!$initnum[$i]){
                    throw new \Exception('闪购数量不能为空！');
                }
                $goods['store_pid'] = $store_pid[$i];
                $goods['tid'] = $tid;
                $goods['special_id'] = $time_data['special_id'];
                $goods['promotion_price'] = $promotion_price[$i];
                $goods['ini_y_tnum'] = $initnum[$i];
                $goods['initnum'] = $initnum[$i];
                //$goods['repertory_num'] = (int)$initnum[$i] * rand(10,20); //虚拟库存
                //dump($goods);
                $stattus = M('starbuy_flashsales_goods')->add($goods);
                if($stattus === false){
                    throw new \Exception('失败');
                }

                //闪购借库存（冻结库存加上闪购数量）
                $s_p_data = M('b2c_store_product')->where(['store_pid' => $goods['store_pid'], 'store_status' => 'true'])->find();
                //$updata['store'] = $s_p_data['store'] - $goods['initnum'];
                //可用库存
                /*$storeNum = $s_p_data['store'] - $s_p_data['freez'];
                if($storeNum < $goods['initnum']){
                    throw new \Exception('闪购数量不能大于可用库存');
                }*/
                $updata['freez'] = $s_p_data['freez'] + $goods['initnum'];
                $s_p_status = M('b2c_store_product')->where(['store_pid' => $goods['store_pid'], 'store_status' => 'true'])->save($updata);

                //$s_p_status = M('b2c_store_product')->where(['store_pid' => $goods['store_pid']])->setInc('freez',$goods['initnum']);
                if($s_p_status === false){
                    throw new \Exception('失败');
                }
                //把活动商品添加到店铺活动商品中间表
                $activity_data['store_id'] = $store_pid[$i];
                $activity_data['local_id'] = $this->local_id;
                $activity_data['type'] = 1;
                $activity_data['start_time'] = $time_data['begin_time'];
                $activity_data['end_time'] = $time_data['end_time'];
                if(M('store_activity_product')->where(['store_id'=>$store_pid[$i]])->find()){
                    $stattus = M('store_activity_product')->where(['store_id'=>$store_pid[$i]])->save($activity_data);
                }else{
                    $stattus = M('store_activity_product')->add($activity_data);
                }
                if($stattus === false){
                    throw new \Exception('失败');
                }
            }
            // 提交事务
            $model->commit();

            $this->success('成功',U('Flashsales/timeIndex',['special_id'=>I('special_id',0)]));
        }catch (\Exception $msg){
            // 事务回滚
            $model->rollback();
            $this->error('错误提示：' . $msg->getMessage());
        }

    }
    /**
     * 删除闪购信息
     * @param $id 闪购ID
     */
    public function fastDelete(){
        $model = M();
        $tid = I('tid',0) or $this->ajaxReturn(['status'=>false,'msg'=>'参数错误']);
        if(is_numeric($tid)){
            $this->ajaxReturn(['status'=>false,'msg'=>'参数错误']);
        }
        $data = M('starbuy_flashsales_time')->where(['tid'=>$tid])->find();
        $time = time();
        //进行中不许删除数据
        if($data['begin_time'] < $time && $time< $data['end_time']){
            $this->ajaxReturn(['status'=>false,'msg'=>'闪购正在进行中不能删除']);
        }
        $good_data = M('starbuy_flashsales_goods')->where(array('tid'=>$data['tid']))->select();
        try{
            $model->execute('begin');
            $stat = M('starbuy_flashsales_time')->where(['tid'=>$tid])->delete();
            if($stat === false){
                throw new \Exception('删除失败');
            }
            foreach($good_data as $k1 => $v1){
               /* $s_p_data = M('b2c_store_product')->where(['store_pid' => $v1['store_pid']])->find();
                $updata['store'] = $s_p_data['store'] + $v1['initnum'];
                $updata['freez'] = $s_p_data['freez'] - $v1['initnum'];
                $s_p_status = M('b2c_store_product')->where(['store_pid' => $v1['store_pid']])->save($updata);*/

                $s_p_status = M('b2c_store_product')->where(['store_pid' => $v1['store_pid'], 'store_status' => 'true'])->setDec('freez',$v1['initnum']);
                if($s_p_status === false){
                    throw new \Exception('删除失败');
                }
            }
            $status = M('starbuy_flashsales_goods')->where(array('tid'=>$data['tid']))->delete();
            if($status === false){
                throw new \Exception('删除失败');
            }
            // 提交事务
            $model->execute('commit');
            $this->ajaxReturn(['status'=>true,'msg'=>'删除成功']);
        }catch (\Exception $msg){
            // 事务回滚
            $model->execute('rollback');
            $this->ajaxReturn(['status'=>false,'msg'=>$msg]);
        }
    }

    /**
     * 删除货品
     * @param $tid
     * @param $s_id
     */
    public function productDel(){
        $model = M();
        $tid = I('tid',0) or $this->ajaxReturn(['status'=>false,'msg'=>'参数错误']);
        if(is_numeric($tid)){
            $this->ajaxReturn(['status'=>false,'msg'=>'参数错误']);
        }
        $store_pid = I('store_pid',0) or $this->ajaxReturn(['status'=>false,'msg'=>'参数错误']);
        if(is_numeric($store_pid)){
            $this->ajaxReturn(['status'=>false,'msg'=>'参数错误']);
        }
        $good_data = M('starbuy_flashsales_goods')->where(array('tid'=>$tid,'store_pid'=>$store_pid))->find();
        if(!$good_data){
            $this->ajaxReturn(['status'=>false,'msg'=>'该货品已删除请勿重复操作！']);
        }
       /* $s_p_data = M('b2c_store_product')->where(['store_pid' => $good_data['store_pid']])->find();
        $updata['store'] = $s_p_data['store'] + $good_data['initnum'];
        $updata['freez'] = $s_p_data['freez'] - $good_data['initnum'];*/
        try{
            $model->execute('begin');
            //返回库存
            $s_p_status = M('b2c_store_product')->where(['store_pid' => $good_data['store_pid'], 'store_status' => 'true'])->setDec('freez',$good_data['initnum']);
            if($s_p_status === false){
                throw new \Exception('删除失败');
            }
            $status = M('starbuy_flashsales_goods')->where(array('tid'=>$tid,'store_pid'=>$store_pid))->delete();
            if($status === false){
                throw new \Exception('删除失败');
            }
            // 提交事务
            $model->execute('commit');
            $this->ajaxReturn(['status'=>true,'msg'=>'删除成功']);
        }catch (\Exception $msg){
            // 事务回滚
            $model->execute('rollback');
            $this->ajaxReturn(['status'=>false,'msg'=>$msg]);
        }

    }




    public function __destruct()
    {
        parent::__destruct();
        unset($this->obj);
        unset($this->time_obj);
        unset($this->product_obj);
    }


}